package cn.iocoder.yudao.module.trade.service.order;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.trade.controller.admin.order.vo.TradeOrderPageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.order.vo.TradeOrderSaveReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.ORDER_NOT_FOUND;

/**
 * 贵金属交易订单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class TradeOrderServiceImpl implements TradeOrderService {

    @Resource
    private TradeOrderMapper orderMapper;

    @Override
    public String createOrderMetals(TradeOrderSaveReqVO createReqVO) {
        // 插入
        TradeOrderDO order = BeanUtils.toBean(createReqVO, TradeOrderDO.class);
        orderMapper.insert(order);
        // 返回
        return order.getOrderNo();
    }

    @Override
    public void updateOrderMetals(TradeOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderMetalsExists(updateReqVO.getOrderNo());
        // 更新
        TradeOrderDO updateObj = BeanUtils.toBean(updateReqVO, TradeOrderDO.class);
        orderMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderMetals(String id) {
        // 校验存在
        validateOrderMetalsExists(id);
        // 删除
        orderMapper.deleteById(id);
    }

    private TradeOrderDO validateOrderMetalsExists(String id) {
        TradeOrderDO tradeOrderDO = orderMapper.selectByNo(id);
        if ( tradeOrderDO== null) {
            throw exception(ORDER_NOT_FOUND);
        }
        return tradeOrderDO;
    }

    @Override
    public TradeOrderDO getOrderMetals(String id) {
        return orderMapper.selectById(id);
    }

    @Override
    public PageResult<TradeOrderDO> getOrderMetalsPage(TradeOrderPageReqVO pageReqVO) {
        return orderMapper.selectPage(pageReqVO);
    }

    @Override
    public TradeOrderDO getOrderByPickUpVerify(String code) {
        TradeOrderDO order = orderMapper.selectOneByPickUpVerifyCode(code);
        if (order == null) {
            throw exception(ORDER_NOT_FOUND);
        }
        return order;
    }

}